package v1

import (
	"supervideo/app/models/zone"
	"supervideo/app/requests"
	"supervideo/pkg/response"

	"github.com/gin-gonic/gin"
)

type ZoneController struct {
	BaseAdminController
}

func (zc *ZoneController) Index(c *gin.Context) {
	request := requests.PaginationRequest{}

	if ok := requests.Validate(c, &request, requests.Pagination); !ok {
		return
	}

	data, pager := zone.Paginate(c, 10)
	response.JSON(c, gin.H{
		"data":  data,
		"pager": pager,
	})
}

func (zc *ZoneController) Store(c *gin.Context) {
	request := requests.ZoneRequest{}
	if ok := requests.Validate(c, &request, requests.ZoneStore); !ok {
		return
	}

	zoneModel := zone.Zone{
		Title:  request.Title,
		Sort:   request.Sort,
		Status: request.Status,
	}

	zoneModel.Create()
	if zoneModel.ID > 0 {
		response.Created(c, zoneModel)
	} else {
		response.Abort500(c, "创建失败, 请稍后重试~")
	}
}

func (zc *ZoneController) Update(c *gin.Context) {
	zoneModel := zone.Get(c.Param("id"))
	if zoneModel.ID == 0 {
		response.Abort404(c)
		return
	}

	request := requests.ZoneRequest{}
	if ok := requests.Validate(c, &request, requests.ZoneStore); !ok {
		return
	}

	zoneModel.Title = request.Title
	zoneModel.Sort = request.Sort
	zoneModel.Status = request.Status
	rowAffected := zoneModel.Save()
	if rowAffected > 0 {
		response.Data(c, zoneModel)
	} else {
		response.Abort500(c, "更新失败, 请稍后尝试~")
	}

}

func (zc *ZoneController) Delete(c *gin.Context) {
	zoneModel := zone.Get(c.Param("id"))
	if zoneModel.ID == 0 {
		response.Abort404(c)
		return
	}

	rowAffected := zoneModel.Delete()
	if rowAffected > 0 {
		response.Success(c)
		return
	}

	response.Abort500(c, "删除失败,请稍后尝试~")

}

func (zc *ZoneController) Show(c *gin.Context) {
	zoneModel := zone.Get(c.Param("id"))
	if zoneModel.ID == 0 {
		response.Abort404(c)
		return
	}
	response.Data(c, zoneModel)
}
